package com.adou.service.impl;

import com.adou.common.dto.WorkAttachOutDto;
import com.adou.common.mapper.*;
import com.adou.common.model.*;
import com.adou.common.util.*;
import com.adou.common.util.userauth.interfaceUtils;
import com.adou.service.FlowMainFileService;
import com.adou.service.impl.base.BaseServiceImp;
import com.adou.shiro.token.TokenManager;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class FlowMainFileServiceImpl extends BaseServiceImp<FlowMainFile> implements FlowMainFileService {

    @Autowired
    private FlowMainFileMapper flowMainFileMapper;

    @Autowired
    private FlowTaskMapper flowTaskMapper;

    @Autowired
    private FlowDirectionMapper flowDirectionMapper;

    @Autowired
    private FlowHistoryMapper flowHistoryMapper;

    @Autowired
    private FlowMainMapper flowMainMapper;

    @Autowired
    private WorkAttachMapper workAttachMapper;

    @Autowired
    private HttpServletRequest request;

    @Override
    public Map<String, Object> insertSelective(Map<String, Object> map) {
        //根据流向查询开始节点
        Map<String, Object> resultMap = new HashMap<>();
        if (StringUtil.isBlank(map.get("ifmid"))) {
            resultMap.put("result", 203);
            resultMap.put("msg", "ifmid为空");
            return resultMap;
        }
        if (StringUtil.isBlank(map.get("ctitle"))) {
            resultMap.put("result", 204);
            resultMap.put("msg", "标题为空");
            return resultMap;
        }
        FlowMainFile flowMainFile = new FlowMainFile();
        flowMainFile.setIfmid(Long.parseLong(map.get("ifmid").toString()));
        flowMainFile.setCcreator(TokenManager.getUserNameByKey());
        flowMainFile.setCtitle(map.get("ctitle").toString());
        List<FlowDirection> flowDirectionList = flowDirectionMapper.queryStartDirection(flowMainFile.getIfmid());
        if (flowDirectionList.size() == 0) {
            resultMap.put("result", 205);
            resultMap.put("msg", "未设置起始节点");
            return resultMap;
        }
        flowMainFile.setCcurtid(flowDirectionList.get(0).getIstartftid());
        FlowTask ft = getFlowTaskById(flowMainFile.getCcurtid());
        if (ft == null) {
            resultMap.put("result", 206);
            resultMap.put("msg", "节点错误");
            return resultMap;
        }
        flowMainFile.setCcurtname(ft.getCtaskname());
        flowMainFile.setCctrola(ft.getCctrola());
        flowMainFile.setCctrolb(ft.getCctrolb());
        flowMainFile.setCctrolc(ft.getCctrolc());
        flowMainFile.setCctrold(ft.getCctrold());
        flowMainFile.setCprochistory("启动流程");
        flowMainFile.setCtodoids(TokenManager.getIdByKey().toString());
        flowMainFile.setCtodousers(flowMainFile.getCcreator());
        int res = flowMainFileMapper.insert(flowMainFile);
        if (res > 0) {
            resultMap.put("msg", "流程启动成功");
            FlowHistory flowHistory = new FlowHistory(flowMainFile.getId(), flowMainFile.getCcreator(),
                    flowMainFile.getCcurtname(), "启动流程", null);
            flowHistoryMapper.insert(flowHistory);
        }
        resultMap.put("data", flowMainFile);
        return resultMap;
    }

    @Override
    public Map<String, Object> pageList(int pageNum, int pageSize, Map<String, Object> map) {
        Page<?> page = PageHelper.startPage(pageNum, pageSize);
        map.put("uid", TokenManager.getIdByKey());
        List<Map<String, Object>> flowMainFileList = flowMainFileMapper.pageList(map);
        if (map.get("p").equals("0")) {
            for (Map<String, Object> map1 : flowMainFileList) {
                Long taskid = Long.parseLong(map1.get("ccurtid").toString());
                Long ifmid = Long.parseLong(map1.get("ifmid").toString());
                List<FlowDirection> flowDirectionList = flowDirectionMapper.queryStartDirection(ifmid);
                if (flowDirectionList.size() > 0 && flowDirectionList.get(0).getIstartftid().longValue() == taskid.longValue()) {
                    map1.put("isStart", true);
                }
            }
        }
        Map<String, Object> data = new HashMap<>();
        data.put("totalpage", page.getPages());
        data.put("totalcount", page.getTotal());
        data.put("pageNum", pageNum);
        data.put("pageSize", pageSize);
        data.put("list", flowMainFileList);
        return data;
    }

    @Override
    public int delete(FlowMainFile o) {
        List<FlowMainFile> flowMainFileList = flowMainFileMapper.find(o);
        if (flowMainFileList.size() != 1) {
            //流程不存在
            return -1;
        }
        FlowMainFile flowMainFile = flowMainFileList.get(0);
        if (flowMainFile.getBflag()) {
            //办结无法删除
            return -2;
        }
        if (flowMainFile.getBsigflag()) {
            //已签收 无法删除
            return -3;
        }
        FlowMain flowMain = new FlowMain();
        flowMain.setId(flowMainFile.getIfmid());
        List<FlowMain> flowMainList = flowMainMapper.find(flowMain);
        if (flowMainList.size() != 1) {
            //流程定义表数据不存在
            return -4;
        }
        flowMain = flowMainList.get(0);
        if (!("," + flowMain.getAdminId() + ",").contains("," + TokenManager.getIdByKey() + ",") &&
                !TokenManager.getUserNameByKey().equals(flowMainFile.getCcreator())) {
            //当前用户无删除权限 管理员 创建者 有权删除
            return -5;
        }
        //非管理员判断是否是初始阶段
        if (!("," + flowMain.getAdminId() + ",").contains("," + TokenManager.getIdByKey() + ",")) {
            List<FlowDirection> flowDirectionList = flowDirectionMapper.queryStartDirection(flowMainFile.getIfmid());
            if (flowDirectionList.size() == 1 && flowDirectionList.get(0).getIstartftid().longValue() != flowMainFile.getCcurtid().longValue()) {
                //非初始阶段 无权删除
                return -6;
            }
        }
        StringBuffer sql = new StringBuffer();
        sql.append("DELETE FROM ");
        sql.append(flowMain.getCformident());
        sql.append(" WHERE iflowId = " + o.getId());
        flowMainFileMapper.deleteTableData(sql.toString());
        FlowHistory flowHistory = new FlowHistory();
        flowHistory.setIflid(o.getId());
        flowHistoryMapper.delete(flowHistory);
        WorkAttach workAttach = new WorkAttach();
        workAttach.setIflid(o.getId());
        deleteFiles(workAttach);
        workAttachMapper.delete(workAttach);
        return super.delete(o);
    }

    @Override
    public List<FlowMain> queryFlowListById() {
        FlowMain flowMain = new FlowMain();
        flowMain.setCflowids(TokenManager.getIdByKey().toString());
        flowMain.setBstate(true);
        return flowMainMapper.find(flowMain);
    }

    @Override
    public Map<String, Object> getFormDataByIfmid(Long ifmid) {
        return flowMainFileMapper.getFormDataByIfmid(ifmid);
    }

    @Override
    public Map<String, Object> getFormDataById(Long id) {
        Map<String, Object> resultMap = new HashMap<>();
        String tableName = flowMainFileMapper.getTableNameById(id);
        if (StringUtil.isBlank(tableName)) {
            resultMap.put("result", 104);
            resultMap.put("msg", "无相关表单");
            return resultMap;
        }
        StringBuffer sb = new StringBuffer();
        sb.append("SELECT * FROM ");
        sb.append(tableName);
        sb.append(" WHERE iflowid = " + id);
        Map<String, Object> data = flowMainFileMapper.queryFormData(sb.toString());
        if (data != null && !data.isEmpty()) {
            WorkAttach workAttach = new WorkAttach();
            workAttach.setIflid(id);
            List<WorkAttach> workAttachList = workAttachMapper.find(workAttach);
            if(workAttachList.size() > 0){
                List<Map<String, Object>> fileList = new ArrayList<>();
                Map<String, Object> m;
                StringBuffer serverUrl = new StringBuffer();
                serverUrl.append(request.getScheme());
                serverUrl.append("://");
                serverUrl.append(request.getServerName());
                serverUrl.append(":");
                serverUrl.append(request.getServerPort());
                serverUrl.append(request.getContextPath());
                serverUrl.append("/");
                for (WorkAttach w: workAttachList) {
                    m = new HashMap<>();
                    m.put("realName", w.getCrealname());
                    if(w.getCpath().equals(IConfig.get("picPath"))){
                        m.put("type", "pic");
                    } else {
                        m.put("type", "file");
                    }
                    m.put("path", serverUrl + w.getCpath() + w.getCfilename());
                    fileList.add(m);
                }
                resultMap.put("fileList", fileList);
            }
            resultMap.put("data", data);
            resultMap.put("result", 1);
            resultMap.put("msg", "操作成功");
        } else {
            resultMap.put("result", 103);
            resultMap.put("msg", "未查询到数据");
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> fillForm(Map<String, Object> map) {
        Map<String, Object> resultMap = new HashMap<>();
        //查看下一节点
        long ccurtid = Long.parseLong(map.get("ccurtid").toString());
        long ifmid = Long.parseLong(map.get("ifmid").toString());
        long id = Long.parseLong(map.get("id").toString());

        FlowTask flowTask = new FlowTask();
        flowTask.setId(ccurtid);
        List<FlowTask> flowTaskList = flowTaskMapper.find(flowTask);
        if(flowTaskList.size() == 1){
            flowTask = flowTaskList.get(0);
            if(flowTask.getbIsNotes() != null && flowTask.getbIsNotes()){
                if(StringUtil.isBlank(map.get("cnotes"))){
                    //输入办理意见
                    resultMap.put("result", 9);
                    resultMap.put("msg", "请输入签署意见");
                    return resultMap;
                }
            }
        } else {
            resultMap.put("result", 201);
            resultMap.put("msg", "节点不存在");
            return resultMap;
        }

        List<FlowDirection> flowDirectionList = getNextNode(ccurtid, ifmid);
        if (flowDirectionList.size() == 0) {
            resultMap.put("result", 2);
            resultMap.put("msg", "无下一节点");
            return resultMap;
        }
        if (flowDirectionList.size() == 1) {
            FlowDirection f = flowDirectionList.get(0);
            FlowMainFile flowMainFile = new FlowMainFile();
            flowMainFile.setId(id);
            flowMainFile.setCcurtid(f.getIendftid());
            if (flowDirectionMapper.checkIsEnd(f).size() > 0) {
                //进入办结
                if (StringUtil.isBlank(map.get("cnotes"))) {
                    resultMap.put("result", 6);
                    resultMap.put("msg", "流程办结请输入办理意见");
                    return resultMap;
                }
                flowMainFile.setBflag(true);
                flowMainFile.setCnotes(map.get("cnotes").toString());
                flowMainFile.setCdoneids(TokenManager.getIdByKey().toString());
                flowMainFile.setCdoneusers(TokenManager.getUserNameByKey());
                flowMainFile.setCprochistory("流程办结");
                flowMainFile.setCcurtname("流程办结");
                flowMainFile.setCbedoingids("");
                flowMainFile.setCbedoingusers("");
                flowMainFile.setCtodoids("");
                flowMainFile.setCtodousers("");
                flowMainFile = setDoneUserAndHistory(flowMainFile);
                int res = flowMainFileMapper.update(flowMainFile);
                if (res > 0) {
                    resultMap.put("result", 1);
                    resultMap.put("msg", "流程办结");
                    FlowHistory fh = new FlowHistory(flowMainFile.getId(), TokenManager.getUserNameByKey(),
                            flowMainFile.getCcurtname(), "流程办结", flowMainFile.getCnotes());
                    flowHistoryMapper.insert(fh);
                }
                return resultMap;
            }
            FlowTask ft = getFlowTaskById(f.getIendftid());
            if (ft != null) {
                flowMainFile.setCcurtname(ft.getCtaskname());
                flowMainFile.setCctrola(ft.getCctrola());
                flowMainFile.setCctrolb(ft.getCctrolb());
                flowMainFile.setCctrolc(ft.getCctrolc());
                flowMainFile.setCctrold(ft.getCctrold());
                if (StringUtil.isBlank(ft.getCconductusers())) {
                    resultMap.put("result", 5);
                    resultMap.put("msg", "下一节点无办理人，无法进入下一节点");
                    return resultMap;
                }
                if (ft.getCconductusers().indexOf(",") > 0) {
                    resultMap.put("result", 3);
                    resultMap.put("msg", "办理人复数，进入节点选择");
                    return resultMap;
                } else {
                    flowMainFile.setCtodoids(ft.getCconductids());
                    flowMainFile.setCtodousers(ft.getCconductusers());
                    flowMainFile.setCdoneids(TokenManager.getIdByKey().toString());
                    flowMainFile.setCdoneusers(TokenManager.getUserNameByKey());
                    flowMainFile.setCprochistory("填写表单");
                    flowMainFile = setDoneUserAndHistory(flowMainFile);
                    flowMainFile.setBsigflag(false);
                    flowMainFile.setCbedoingids("");
                    flowMainFile.setCbedoingusers("");
                    int res = flowMainFileMapper.update(flowMainFile);
                    if (res > 0) {
                        //默认可编辑（不可编辑，跳过保存表单数据，只修改流程状态）
                        if (ft.getbIsEdit() != null && !ft.getbIsEdit()) {
                            resultMap.put("result", 7);
                        } else {
                            resultMap.put("result", 1);
                        }
                        resultMap.put("msg", "提交成功");
                        FlowHistory fh = new FlowHistory(flowMainFile.getId(), TokenManager.getUserNameByKey(),
                                flowMainFile.getCcurtname(), "提交表单", map.get("cnotes") == null ? null : map.get("cnotes").toString());
                        flowHistoryMapper.insert(fh);
                    }
                }
            } else {
                resultMap.put("result", 4);
                resultMap.put("msg", "节点错误");
                return resultMap;
            }
        } else {
            resultMap.put("result", 3);
            resultMap.put("msg", "多个下一节点，进入节点选择");
            resultMap.put("data", flowDirectionList);
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> reFill(Map<String, Object> map) {
        Map<String, Object> resultMap = new HashMap<>();
        long ccurtid = Long.parseLong(map.get("ccurtid").toString());
        long id = Long.parseLong(map.get("id").toString());

        FlowTask flowTask = new FlowTask();
        flowTask.setId(ccurtid);
        List<FlowTask> flowTaskList = flowTaskMapper.find(flowTask);
        if(flowTaskList.size() == 1){
            flowTask = flowTaskList.get(0);
            if(flowTask.getbIsNotes() != null && flowTask.getbIsNotes()){
                if(StringUtil.isBlank(map.get("cnotes"))){
                    //输入办理意见
                    resultMap.put("result", 9);
                    resultMap.put("msg", "请输入签署意见");
                    return resultMap;
                }
            }
        } else {
            resultMap.put("result", 201);
            resultMap.put("msg", "节点不存在");
            return resultMap;
        }

        FlowTask ft = getFlowTaskById(ccurtid);
        FlowMainFile flowMainFile = new FlowMainFile();
        flowMainFile.setId(id);
        FlowDirection flowDirection = new FlowDirection();
        flowDirection.setIendftid(ccurtid);
        flowDirection.setIfmid(Long.parseLong(map.get("ifmid").toString()));
        List<FlowDirection> flowDirectionList = flowDirectionMapper.checkIsEnd(flowDirection);
        if (flowDirectionList.size() > 0) {
            if(StringUtil.isBlank(map.get("cnotes"))){
                resultMap.put("result", 6);
                resultMap.put("msg", "流程办结请输入办理意见");
                return resultMap;
            }
            flowMainFile.setBflag(true);
            flowMainFile.setCnotes(map.get("cnotes").toString());
            flowMainFile.setCdoneids(TokenManager.getIdByKey().toString());
            flowMainFile.setCdoneusers(TokenManager.getUserNameByKey());
            flowMainFile.setCprochistory("流程办结");
            flowMainFile.setCcurtname("流程办结");
            flowMainFile.setCbedoingids("");
            flowMainFile.setCbedoingusers("");
            flowMainFile.setCtodoids("");
            flowMainFile.setCtodousers("");
            flowMainFile = setDoneUserAndHistory(flowMainFile);
            int res = flowMainFileMapper.update(flowMainFile);
            if (res > 0) {
                resultMap.put("result", 1);
                resultMap.put("msg", "流程办结");
                FlowHistory fh = new FlowHistory(flowMainFile.getId(), TokenManager.getUserNameByKey(),
                        flowMainFile.getCcurtname(), "流程办结", flowMainFile.getCnotes());
                flowHistoryMapper.insert(fh);
            }
        } else {
            if (StringUtil.isBlank(map.get("ctodoids"))){
                resultMap.put("result", 207);
                resultMap.put("msg", "请选择办理人");
                return resultMap;
            }
            if (StringUtil.isBlank(map.get("ctodousers"))){
                resultMap.put("result", 208);
                resultMap.put("msg", "请选择办理人");
                return resultMap;
            }
            if(ft.getbIsSign() != null && ft.getbIsSign()){
                if(StringUtil.isBlank(map.get("cnotes"))){
                    //输入办理意见
                    resultMap.put("result", 9);
                    resultMap.put("msg", "请输入签署意见");
                    return resultMap;
                }
            }
            flowMainFile.setCcurtid(ccurtid);
            flowMainFile.setCcurtname(ft.getCtaskname());
            flowMainFile.setCctrola(ft.getCctrola());
            flowMainFile.setCctrolb(ft.getCctrolb());
            flowMainFile.setCctrolc(ft.getCctrolc());
            flowMainFile.setCctrold(ft.getCctrold());
            flowMainFile.setCtodoids(map.get("ctodoids").toString());
            flowMainFile.setCtodousers(map.get("ctodousers").toString());
            flowMainFile.setCdoneids(TokenManager.getIdByKey().toString());
            flowMainFile.setCdoneusers(TokenManager.getUserNameByKey());
            flowMainFile.setCprochistory("填写表单");
            flowMainFile.setCbedoingusers("");
            flowMainFile.setCbedoingids("");
            flowMainFile.setBsigflag(false);
            flowMainFile = setDoneUserAndHistory(flowMainFile);
            int res = flowMainFileMapper.update(flowMainFile);
            if (res > 0) {
                if (ft.getbIsEdit() != null && !ft.getbIsEdit()) {
                    resultMap.put("result", 7);
                } else {
                    resultMap.put("result", 1);
                }
                resultMap.put("msg", "提交成功");
                FlowHistory fh = new FlowHistory(flowMainFile.getId(), TokenManager.getUserNameByKey(),
                        flowMainFile.getCcurtname(), "提交表单", map.get("cnotes") == null ? null : map.get("cnotes").toString());
                flowHistoryMapper.insert(fh);
            }
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> backFlow(Long id) {
        Map<String, Object> resultMap = new HashMap<>();
        FlowMainFile flowMainFile = new FlowMainFile();
        flowMainFile.setId(id);
        List<FlowMainFile> flowMainFileList = flowMainFileMapper.find(flowMainFile);
        if (flowMainFileList.size() == 0) {
            resultMap.put("result", 303);
            resultMap.put("msg", "未查询到相关流程实例，无法撤销");
            return resultMap;
        }
        flowMainFile = flowMainFileList.get(0);
        if (flowMainFile.getBflag()) {
            resultMap.put("result", 305);
            resultMap.put("msg", "流程已办结，无法撤销");
            return resultMap;
        }
        if (flowMainFile.getBsigflag()) {
            resultMap.put("result", 304);
            resultMap.put("msg", "用户【 " + flowMainFile.getCbedoingusers() + " 】已签收，无法撤销");
            return resultMap;
        }
        String[] idList = flowMainFile.getCdoneids().split(",");
        if (!idList[idList.length - 1].equals(TokenManager.getIdByKey().toString())) {
            resultMap.put("result", 306);
            resultMap.put("msg", "当前阶段用户无权限撤销");
            return resultMap;
        }
        FlowDirection flowDirection = new FlowDirection();
        flowDirection.setIendftid(flowMainFile.getCcurtid());
        flowDirection.setIfmid(flowMainFile.getIfmid());
        FlowDirection f = flowDirectionMapper.queryStartDirection(flowMainFile.getIfmid()).get(0);
        List<FlowDirection> flowDirectionList = flowDirectionMapper.find(flowDirection);
        if (f.getIstartftid().longValue() == flowMainFile.getCcurtid().longValue()) {
            resultMap.put("result", 307);
            resultMap.put("msg", "初始节点，无法撤销");
            return resultMap;
        }
        if (flowDirectionList.size() > 1) {
            FlowHistory flowHistory = new FlowHistory();
            flowHistory.setIflid(flowMainFile.getId());
            List<FlowHistory> flowHistoryList = flowHistoryMapper.find(flowHistory);
            if (flowHistoryList.size() > 1) {
                flowHistory = flowHistoryList.get(1);
                for (FlowDirection flowDirection1 : flowDirectionList) {
                    FlowTask ft = getFlowTaskById(flowDirection1.getIstartftid());
                    if (ft != null) {
                        if (ft.getCtaskname().equals(flowHistory.getCtaskname())
                                && ft.getCconductusers().contains(flowHistory.getCdone())) {
                            flowDirection = flowDirection1;
                            break;
                        }
                    }
                }
            } else {
                resultMap.put("result", 310);
                resultMap.put("msg", "记录出错，无法撤销");
                return resultMap;
            }
        } else {
            flowDirection = flowDirectionList.get(0);
        }
        FlowTask flowTask = getFlowTaskById(flowDirection.getIstartftid());
        if (flowTask == null) {
            resultMap.put("result", 309);
            resultMap.put("msg", "流程节点不存在，无法撤销");
            return resultMap;
        }
        flowMainFile.setCcurtid(flowTask.getId());
        flowMainFile.setCcurtname(flowTask.getCtaskname());
        flowMainFile.setCctrola(flowTask.getCctrola());
        flowMainFile.setCctrolb(flowTask.getCctrolb());
        flowMainFile.setCctrolc(flowTask.getCctrolc());
        flowMainFile.setCctrold(flowTask.getCctrold());
        String ids = flowMainFile.getCdoneids();
        String names = flowMainFile.getCdoneusers();
        flowMainFile.setCtodousers(names.substring(names.lastIndexOf(",") == -1 ? 0 : names.lastIndexOf(",") + 1));
        flowMainFile.setCtodoids(ids.substring(ids.lastIndexOf(",") == -1 ? 0 : ids.lastIndexOf(",") + 1));
        flowMainFile.setCdoneusers(names.substring(0, names.lastIndexOf(",") == -1 ? 0 : names.lastIndexOf(",")));
        flowMainFile.setCdoneids(ids.substring(0, ids.lastIndexOf(",") == -1 ? 0 : ids.lastIndexOf(",")));
        flowMainFile.setCprochistory(flowMainFile.getCprochistory() + ",撤销流程");
        int res = flowMainFileMapper.update(flowMainFile);
        if (res > 0) {
            resultMap.put("result", 1);
            resultMap.put("msg", "撤销流程成功");
            FlowHistory fh = new FlowHistory(flowMainFile.getId(), TokenManager.getUserNameByKey(),
                    flowMainFile.getCcurtname(), "撤销流程", null);
            flowHistoryMapper.insert(fh);
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> signFlow(Long id) {
        Map<String, Object> resultMap = new HashMap<>();
        FlowMainFile flowMainFile = new FlowMainFile();
        flowMainFile.setId(id);
        List<FlowMainFile> flowMainFileList = flowMainFileMapper.find(flowMainFile);
        if (flowMainFileList.size() == 1) {
            FlowMainFile f = flowMainFileList.get(0);
            if (f.getBsigflag()) {
                resultMap.put("result", 304);
                resultMap.put("msg", f.getCbedoingusers() + "已签收，无法再次签收");
            } else if (!("," + f.getCtodoids() + ",").contains("," + TokenManager.getIdByKey() + ",")) {
                resultMap.put("result", 305);
                resultMap.put("msg", "当前用户无签收权限");
            } else {
                if (StringUtil.isNotBlank(f.getCbedoingids()) && StringUtil.isNotBlank(f.getCbedoingusers())) {
                    f.setCbedoingids(f.getCbedoingids() + "," + TokenManager.getIdByKey().toString());
                    f.setCbedoingusers(f.getCbedoingusers() + "," + TokenManager.getUserNameByKey());
                } else {
                    f.setCbedoingids(TokenManager.getIdByKey().toString());
                    f.setCbedoingusers(TokenManager.getUserNameByKey());
                }
                f.setCprochistory(f.getCprochistory() + ",签收");
                f.setBsigflag(true);
                f.setDsigtime(new Date());
                int res = flowMainFileMapper.update(f);
                if (res > 0) {
                    resultMap.put("result", 1);
                    resultMap.put("msg", "签收成功");
                    FlowHistory fh = new FlowHistory(f.getId(), TokenManager.getUserNameByKey(),
                            f.getCcurtname(), "签收", null);
                    flowHistoryMapper.insert(fh);
                }
            }
        } else {
            resultMap.put("result", 303);
            resultMap.put("msg", "流程不存在");
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> returnFlow(Long id, String note) {
        Map<String, Object> resultMap = new HashMap<>();
        FlowMainFile flowMainFile = new FlowMainFile();
        flowMainFile.setId(id);
        List<FlowMainFile> flowMainFileList = flowMainFileMapper.find(flowMainFile);
        if (flowMainFileList.size() == 1) {
            FlowMainFile f = flowMainFileList.get(0);
            if (!("," + f.getCtodoids() + ",").contains("," + TokenManager.getIdByKey() + ",")) {
                resultMap.put("result", 304);
                resultMap.put("msg", "用户无退回权限");
                return resultMap;
            }
            if (f.getBflag()) {
                resultMap.put("result", 311);
                resultMap.put("msg", "流程已办结，无法退回");
                return resultMap;
            }
            FlowTask flowTask = getFlowTaskById(f.getCcurtid());
            if (flowTask != null) {
                if (flowTask.getbIsReturn() != null && flowTask.getbIsReturn()) {
                    FlowDirection flowDirection = new FlowDirection();
                    flowDirection.setIendftid(flowTask.getId());
                    flowDirection.setIfmid(flowTask.getIfmid());
                    List<FlowDirection> flowDirectionList = flowDirectionMapper.find(flowDirection);
                    if (flowDirectionList.size() == 0) {
                        resultMap.put("result", 308);
                        resultMap.put("msg", "不存在上位节点，不允许退回");
                        return resultMap;
                    }
                    if (flowDirectionList.size() > 1) {
                        FlowHistory flowHistory = new FlowHistory();
                        flowHistory.setIflid(flowMainFile.getId());
                        List<FlowHistory> flowHistoryList = flowHistoryMapper.find(flowHistory);
                        if (flowHistoryList.size() > 1) {
                            flowHistory = flowHistoryList.get(1);
                            for (FlowDirection flowDirection1 : flowDirectionList) {
                                FlowTask ft = getFlowTaskById(flowDirection1.getIstartftid());
                                if (ft != null) {
                                    if (ft.getCtaskname().equals(flowHistory.getCtaskname())
                                            && ft.getCconductusers().contains(flowHistory.getCdone())) {
                                        flowDirection = flowDirection1;
                                        break;
                                    }
                                }
                            }
                        } else {
                            resultMap.put("result", 310);
                            resultMap.put("msg", "记录出错，无法退回");
                            return resultMap;
                        }
                    } else {
                        flowDirection = flowDirectionList.get(0);
                    }
                    flowTask = getFlowTaskById(flowDirection.getIstartftid());
                    if (flowTask != null) {
                        f.setCcurtid(flowTask.getId());
                        f.setCcurtname(flowTask.getCtaskname());
                        f.setCctrola(flowTask.getCctrola());
                        f.setCctrolb(flowTask.getCctrolb());
                        f.setCctrolc(flowTask.getCctrolc());
                        f.setCctrold(flowTask.getCctrold());
                        f.setBsigflag(false);
                        String ids = f.getCdoneids();
                        String names = f.getCdoneusers();
                        f.setCbedoingids("");
                        f.setCbedoingusers("");
                        f.setCtodousers(names.substring(names.lastIndexOf(",") == -1 ? 0 : names.lastIndexOf(",") + 1));
                        f.setCtodoids(ids.substring(ids.lastIndexOf(",") == -1 ? 0 : ids.lastIndexOf(",") + 1));
                        f.setCdoneusers(names.substring(0, names.lastIndexOf(",") == -1 ? 0 : names.lastIndexOf(",")));
                        f.setCdoneids(ids.substring(0, ids.lastIndexOf(",") == -1 ? 0 : ids.lastIndexOf(",")));
                        f.setCprochistory(f.getCprochistory() + ",退回流程");
                        int res = flowMainFileMapper.update(f);
                        if (res > 0) {
                            resultMap.put("result", 1);
                            resultMap.put("msg", "退回流程成功");
                            FlowHistory fh = new FlowHistory(f.getId(), TokenManager.getUserNameByKey(),
                                    f.getCcurtname(), "退回流程", note);
                            flowHistoryMapper.insert(fh);
                        }
                    } else {
                        resultMap.put("result", 310);
                        resultMap.put("msg", "上位节点不存在");
                    }
                } else {
                    resultMap.put("result", 307);
                    resultMap.put("msg", "当前节点不允许退回");
                }
            } else {
                resultMap.put("result", 306);
                resultMap.put("msg", "节点不存在");
            }
        } else {
            resultMap.put("result", 303);
            resultMap.put("msg", "流程不存在");
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> queryDetailById(Long id) {
        Map<String, Object> resultMap = new HashMap<>();
        FlowMainFile flowMainFile = new FlowMainFile();
        flowMainFile.setId(id);
        List<FlowMainFile> flowMainFileList = flowMainFileMapper.find(flowMainFile);
        if (flowMainFileList.size() != 1) {
            resultMap.put("result", 103);
            resultMap.put("msg", "流程办理主表数据不存在");
            return resultMap;
        }
        flowMainFile = flowMainFileList.get(0);
        FlowMain flowMain = new FlowMain();
        flowMain.setId(flowMainFile.getIfmid());
        List<FlowMain> flowMainList = flowMainMapper.find(flowMain);
        if (flowMainList.size() != 1) {
            resultMap.put("result", 104);
            resultMap.put("msg", "流程定义表数据不存在");
            return resultMap;
        }
        flowMain = flowMainList.get(0);
        String tableName = flowMain.getCformident();
        List<Long> longList = flowMainFileMapper.queryFormIdByFormName(tableName);
        if (longList.size() != 1) {
            resultMap.put("result", 105);
            resultMap.put("msg", "表单定义表数据不存在");
            return resultMap;
        }
        Long formId = longList.get(0);
        StringBuffer sb = new StringBuffer();
        sb.append("SELECT * FROM ");
        sb.append(tableName);
        sb.append(" WHERE iflowid = " + id);
        Map<String, Object> resMap = flowMainFileMapper.queryFormData(sb.toString());
        if (resMap == null || resMap.isEmpty()) {
            resultMap.put("result", 106);
            resultMap.put("msg", "表单数据为空");
            return resultMap;
        }
        List<Map<String, Object>> mapList = flowMainFileMapper.queryFields(formId);
        if (mapList.size() == 0) {
            resultMap.put("result", 107);
            resultMap.put("msg", "未查询出相关表单字段定义");
            return resultMap;
        }
        List<Map<String, Object>> list = new ArrayList<>();
        for (Map<String, Object> m : mapList) {
            Map<String, Object> map2 = new HashMap<>();
            map2.put("key", m.get("cfieldName"));
            map2.put("value", resMap.get(m.get("cvalue")));
            list.add(map2);
        }
        resultMap.put("data", list);
        FlowHistory flowHistory = new FlowHistory();
        flowHistory.setIflid(id);
        List<FlowHistory> flowHistoryList = flowHistoryMapper.find(flowHistory);
        if (flowHistoryList.size() > 0) {
            resultMap.put("hData", flowHistoryList);
        }
        WorkAttach workAttach = new WorkAttach();
        workAttach.setIflid(id);
        List<WorkAttach> workAttachList = workAttachMapper.find(workAttach);
        if (workAttachList.size() > 0) {
            List<WorkAttachOutDto> workAttachOutDtoList = workAttachList.stream().map(WorkAttachOutDto::new).collect(Collectors.toList());
            resultMap.put("wData", workAttachOutDtoList);
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> pushTask(Map<String, Object> map) {
        Map<String, Object> resultMap = new HashMap<>();
        if (StringUtil.isBlank(map.get("id"))) {
            resultMap.put("result", 303);
            resultMap.put("msg", "id为空");
            return resultMap;
        }
        if (StringUtil.isBlank(map.get("ctodoids"))) {
            resultMap.put("result", 306);
            resultMap.put("msg", "ctodoids为空");
            return resultMap;
        }
        if (StringUtil.isBlank(map.get("ctodousers"))) {
            resultMap.put("result", 307);
            resultMap.put("msg", "ctodousers为空");
            return resultMap;
        }
        if (StringUtil.isBlank(map.get("ccurtid"))) {
            resultMap.put("result", 308);
            resultMap.put("msg", "ccurtid为空");
            return resultMap;
        }
        FlowTask flowTask = getFlowTaskById(Long.parseLong(map.get("ccurtid").toString()));
        if (flowTask == null) {
            resultMap.put("result", 309);
            resultMap.put("msg", "流程节点不存在");
            return resultMap;
        }
        FlowMainFile flowMainFile = new FlowMainFile();
        flowMainFile.setId(Long.parseLong(map.get("id").toString()));
        List<FlowMainFile> flowMainFileList = flowMainFileMapper.find(flowMainFile);
        if (flowMainFileList.size() != 1) {
            resultMap.put("result", 310);
            resultMap.put("msg", "流程不存在");
            return resultMap;
        }
        flowMainFile = flowMainFileList.get(0);
        if (flowMainFile.getBflag()) {
            resultMap.put("result", 312);
            resultMap.put("msg", "流程已办结，无法特送节点");
            return resultMap;
        }
        flowMainFile.setCcurtid(flowTask.getId());
        flowMainFile.setCcurtname(flowTask.getCtaskname());
        flowMainFile.setCctrola(flowTask.getCctrola());
        flowMainFile.setCctrolb(flowTask.getCctrolb());
        flowMainFile.setCctrolc(flowTask.getCctrolc());
        flowMainFile.setCctrold(flowTask.getCctrold());
        flowMainFile.setCtodoids(map.get("ctodoids").toString());
        flowMainFile.setCtodousers(map.get("ctodousers").toString());
        flowMainFile.setCbedoingids("");
        flowMainFile.setCbedoingusers("");
        flowMainFile.setBsigflag(false);
        flowMainFile.setCprochistory(flowMainFile.getCprochistory() + ",特送节点");
        int res = flowMainFileMapper.update(flowMainFile);
        if (res > 0) {
            resultMap.put("result", 1);
            resultMap.put("msg", "特送节点成功");
            FlowHistory fh = new FlowHistory(flowMainFile.getId(), TokenManager.getUserNameByKey(),
                    flowMainFile.getCcurtname(), "特送节点", null);
            flowHistoryMapper.insert(fh);
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> pushPerson(Map<String, Object> map) {
        Map<String, Object> resultMap = new HashMap<>();
        if (StringUtil.isBlank(map.get("id"))) {
            resultMap.put("result", 303);
            resultMap.put("msg", "id为空");
            return resultMap;
        }
        if (StringUtil.isBlank(map.get("todoids"))) {
            resultMap.put("result", 306);
            resultMap.put("msg", "todoids为空");
            return resultMap;
        }
        if (StringUtil.isBlank(map.get("todousers"))) {
            resultMap.put("result", 307);
            resultMap.put("msg", "todousers为空");
            return resultMap;
        }
        FlowMainFile flowMainFile = new FlowMainFile();
        flowMainFile.setId(Long.parseLong(map.get("id").toString()));
        List<FlowMainFile> flowMainFileList = flowMainFileMapper.find(flowMainFile);
        if (flowMainFileList.size() != 1) {
            resultMap.put("result", 308);
            resultMap.put("msg", "流程不存在");
            return resultMap;
        }
        flowMainFile = flowMainFileList.get(0);
        flowMainFile.setCtodoids(map.get("todoids").toString());
        flowMainFile.setCtodousers(map.get("todousers").toString());
        flowMainFile.setCbedoingids("");
        flowMainFile.setCbedoingusers("");
        flowMainFile.setBsigflag(false);
        flowMainFile.setCprochistory(flowMainFile.getCprochistory() + ",特送个人");
        int res = flowMainFileMapper.update(flowMainFile);
        if (res > 0) {
            resultMap.put("result", 1);
            resultMap.put("msg", "特送个人成功");
            FlowHistory fh = new FlowHistory(flowMainFile.getId(), TokenManager.getUserNameByKey(),
                    flowMainFile.getCcurtname(), "特送个人", null);
            flowHistoryMapper.insert(fh);
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> urgeFlow(Long id) {
        Map<String, Object> resultMap = new HashMap<>();
        FlowMainFile flowMainFile = new FlowMainFile();
        flowMainFile.setId(id);
        List<FlowMainFile> flowMainFileList = flowMainFileMapper.find(flowMainFile);
        if (flowMainFileList.size() != 1) {
            resultMap.put("result", 303);
            resultMap.put("msg", "流程查询错误");
            return resultMap;
        }
        flowMainFile = flowMainFileList.get(0);
        if (flowMainFile.getBflag()) {
            resultMap.put("result", 304);
            resultMap.put("msg", "流程已完结，无法催办");
            return resultMap;
        }
        FlowTask flowTask = getFlowTaskById(flowMainFile.getCcurtid());
        if (flowTask == null) {
            resultMap.put("result", 305);
            resultMap.put("msg", "流程节点不存在");
            return resultMap;
        }
        if (flowTask.getbIsTel() == null || !flowTask.getbIsTel()) {
            resultMap.put("result", 306);
            resultMap.put("msg", "当前节点不允许短信提醒");
            return resultMap;
        }
        String ids;
        if (StringUtil.isNotBlank(flowMainFile.getCbedoingids())) {
            //有正在办理的，给正在办理者发送短信提示
            ids = flowMainFile.getCbedoingids();
        } else if (StringUtil.isBlank(flowMainFile.getCbedoingids()) &&
                StringUtil.isNotBlank(flowMainFile.getCtodoids())) {
            //没有正在办理者，给待签收者发送短信提示
            ids = flowMainFile.getCtodoids();
        } else {
            resultMap.put("result", 307);
            resultMap.put("msg", "无办理者，无法催办");
            return resultMap;
        }
        String memo = "'product':'【提示信息1】','code':'【提示信息2】'";
        String temp = "SMS_9455202";
        JSONObject jsonObject = interfaceUtils.sendTelMsg("ADOA",
                TokenManager.getSessionIdByKey(), TokenManager.getUserIdByKey(),
                ids, temp, memo, "utf-8", UdpGetClientMacAddr.getIP(request));
        if (jsonObject.getIntValue("result") == 1) {
            resultMap.put("msg", "催办成功");
        } else {
            resultMap.put("result", 308);
            resultMap.put("msg", jsonObject.getString("msg"));
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> uploadFileAsync(List<MultipartFile> fileList, WorkAttach workAttach, String type) {
        Map<String, Object> resultMap = new HashMap<>();
        int data = 0;
        if (workAttach.getCident() == null || workAttach.getCident().length() != 59) {
            resultMap.put("result", 203);
            resultMap.put("msg", "标识异常，上传失败");
            return resultMap;
        }
        List<String> listSuf = Arrays.asList(IConfig.get(type + "Suf").split(","));
        if (!checkSuf(fileList, listSuf)) {
            resultMap.put("result", 204);
            resultMap.put("msg", "格式不正确，上传失败");
            return resultMap;
        }
        String path = UtilPath.getRootPath() + IConfig.get(type + "Path");
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        for (MultipartFile f : fileList) {
            if (f != null) {
                String filename = f.getOriginalFilename();
                String suffix = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
                String newName = UUID.randomUUID() + "." + suffix;

                if (type.equals("pic")) {
                    CompressPic compressPic = new CompressPic();
                    String[] wh = IConfig.get("compressPic").split(",");
                    int res = 0;
                    try {
                        res = compressPic.compress(f.getInputStream(), path, newName,
                                Integer.parseInt(wh[0]), Integer.parseInt(wh[1]), true);
                    } catch (IOException e) {
                        logger.error(e.toString());
                    }
                    if (res <= 0) {
                        resultMap.put("result", 205);
                        resultMap.put("msg", "压缩图片出错，上传失败");
                        return resultMap;
                    }
                } else {
                    InputStream in;
                    try (FileOutputStream fos = new FileOutputStream(path + newName)) {
                        in = f.getInputStream();
                        int b;
                        while ((b = in.read()) != -1) {
                            fos.write(b);
                        }
                        fos.close();
                        in.close();
                    } catch (IOException e) {
                        logger.error(e.toString());
                        resultMap.put("result", 206);
                        resultMap.put("msg", "上传文件失败");
                        return resultMap;
                    }
                }
                WorkAttach w = new WorkAttach();
                w.setCrealname(filename);
                w.setCfilename(newName);
                w.setCident(workAttach.getCident());
                w.setUid(TokenManager.getIdByKey());
                w.setCuser(TokenManager.getUserNameByKey());
                w.setIflid(workAttach.getIflid());
                w.setCpath(IConfig.get(type + "Path"));
                w.setItaskid(workAttach.getItaskid());
                w.setCtaskname(workAttach.getCtaskname());
                data += workAttachMapper.insert(w);
            }
        }
        resultMap.put("data", data);
        resultMap.put("msg", "上传成功");
        return resultMap;
    }

    @Override
    public Map<String, Object> deleteFile(Long id) {
        Map<String, Object> resultMap = new HashMap<>();
        if (StringUtil.isBlank(id)) {
            resultMap.put("result", 403);
            resultMap.put("msg", "附件主键为空");
            return resultMap;
        }
        WorkAttach w = new WorkAttach();
        w.setId(id);
        List<WorkAttach> workAttachList = workAttachMapper.find(w);
        if (workAttachList.size() != 1) {
            resultMap.put("result", 405);
            resultMap.put("msg", "附件不存在");
            return resultMap;
        }
        w = workAttachList.get(0);
        if (w.getUid().longValue() != TokenManager.getIdByKey()) {
            resultMap.put("result", 406);
            resultMap.put("msg", "当前用户无权删除此附件");
            return resultMap;
        }
        FlowMainFile flowMainFile = new FlowMainFile();
        flowMainFile.setId(w.getIflid());
        List<FlowMainFile> flowMainFileList = flowMainFileMapper.find(flowMainFile);
        if (flowMainFileList.size() != 1) {
            resultMap.put("result", 407);
            resultMap.put("msg", "主流程不存在");
            return resultMap;
        }
        flowMainFile = flowMainFileList.get(0);
        if (flowMainFile.getBflag()) {
            resultMap.put("result", 408);
            resultMap.put("msg", "主流程已结束，无法删除");
            return resultMap;
        }
        if (w.getItaskid().longValue() != flowMainFile.getCcurtid().longValue()) {
            resultMap.put("result", 409);
            resultMap.put("msg", "附件所属环节与流程当前环节不一致，无法删除");
            return resultMap;
        }
        deleteFiles(w);
        workAttachMapper.delete(w);
        resultMap.put("msg", "删除成功");
        return resultMap;
    }

    /**
     * 校验后缀名
     *
     * @param fileList
     * @param listSuf
     * @return
     */
    private Boolean checkSuf(List<MultipartFile> fileList, List<String> listSuf) {
        for (MultipartFile file : fileList) {
            if (file != null) {
                String filename = file.getOriginalFilename();
                String suf = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
                if (!listSuf.contains(suf)) {
                    return false;
                }
            } else {
                return false;
            }
        }
        return true;
    }

    /**
     * 删除文件
     *
     * @param workAttach
     */
    private void deleteFiles(WorkAttach workAttach) {
        List<WorkAttach> workAttachList = workAttachMapper.find(workAttach);
        if (workAttachList.size() > 0) {
            for (WorkAttach w : workAttachList) {
                String path = UtilPath.getRootPath() + w.getCpath() + w.getCfilename();
                File file = new File(path);
                if (file.exists() && file.isFile()) {
                    file.delete();
                }
            }
        }
    }

    /**
     * 查询下个节点
     *
     * @param ccurtid 当前节点主键
     * @param ifmid   流程定义表主键
     * @return
     */
    private List<FlowDirection> getNextNode(Long ccurtid, Long ifmid) {
        FlowDirection flowDirection = new FlowDirection();
        flowDirection.setIstartftid(ccurtid);
        flowDirection.setIfmid(ifmid);
        List<FlowDirection> flowDirectionList = flowDirectionMapper.find(flowDirection);
        return flowDirectionList;
    }

    /**
     * 查询流程节点
     *
     * @param id
     * @return
     */
    private FlowTask getFlowTaskById(Long id) {
        FlowTask flowTask = new FlowTask();
        flowTask.setId(id);
        List<FlowTask> flowTaskList = flowTaskMapper.find(flowTask);
        if (flowTaskList.size() == 1) {
            return flowTaskList.get(0);
        } else {
            return null;
        }
    }

    /**
     * 配置已完成流程用户与操作记录
     *
     * @param flowMainFile
     * @return
     */
    private FlowMainFile setDoneUserAndHistory(FlowMainFile flowMainFile) {
        List<FlowMainFile> list = flowMainFileMapper.find(flowMainFile);
        if (list.size() > 0) {
            FlowMainFile f = list.get(0);
            if (StringUtil.isNotBlank(f.getCdoneids()) && StringUtil.isNotBlank(f.getCdoneusers())) {
                flowMainFile.setCdoneusers(f.getCdoneusers() + "," + flowMainFile.getCdoneusers());
                flowMainFile.setCdoneids(f.getCdoneids() + "," + flowMainFile.getCdoneids());
            }
            if (f.getCprochistory() != null) {
                flowMainFile.setCprochistory(f.getCprochistory() + "," + flowMainFile.getCprochistory());
            }
            if (StringUtil.isBlank(flowMainFile.getCcurtname())) {
                flowMainFile.setCcurtname(f.getCcurtname());
            }
        }
        return flowMainFile;
    }

}
